package com.xindaoapp.share;

import java.io.File;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.ClipboardManager;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.graphics.Color;
import android.graphics.drawable.PaintDrawable;
import android.net.Uri;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup.LayoutParams;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.Toast;

import com.umeng.socialize.bean.MultiStatus;
import com.umeng.socialize.bean.SHARE_MEDIA;
import com.umeng.socialize.bean.SocializeEntity;
import com.umeng.socialize.controller.UMServiceFactory;
import com.umeng.socialize.controller.UMSocialService;
import com.umeng.socialize.controller.listener.SocializeListeners.MulStatusListener;
import com.umeng.socialize.controller.listener.SocializeListeners.SnsPostListener;
import com.umeng.socialize.controller.listener.SocializeListeners.UMAuthListener;
import com.umeng.socialize.exception.SocializeException;
import com.umeng.socialize.media.QQShareContent;
import com.umeng.socialize.media.QZoneShareContent;
import com.umeng.socialize.media.UMImage;
import com.umeng.socialize.utils.OauthHelper;
import com.umeng.socialize.weixin.media.CircleShareContent;
import com.umeng.socialize.weixin.media.WeiXinShareContent;
import com.xindaoapp.happypet.R;
import com.xindaoapp.happypet.application.HappyPetApplication;
import com.xindaoapp.happypet.protocol.MoccaApi;
import com.xindaoapp.happypet.ui.QuoteFriendActivity;
import com.xindaoapp.happypet.utils.CommonParameter;
import com.xindaoapp.happypet.utils.CommonParameter.UserState;
import com.xindaoapp.happypet.utils.CommonUtil;
import com.xindaoapp.happypet.utils.Constants;
import com.xindaoapp.happypet.utils.IRequest;
import com.xindaoapp.happypet.utils.KeyValuePair;

public class SharePopupWindow extends PopupWindow {

    public static final String PARAM_WEIXIN_APPKEY = "WEIXIN_APPKEY";
    private String mShareContent;
    private String mShareTitle;
    private String mShareUrl;
    private Context mContext;
    public static String sWXAppID;
    private int mShareIconId;
    private String picurl;
    private String mSinaToken;
    // private final String qqAppId = "10021591";
    // private final String qqAppKey = "ush2UkhLR4vh3Qqk";

    private boolean isShowWeiba = false;

    private LinearLayout weiba;

    public UMSocialService mController;

    /**
     * 控制 尾巴好友
     * 
     * @param is
     */
    public void setShowWeiba(boolean is) {
        if (is) {
            weiba.setVisibility(View.VISIBLE);
        } else {
            weiba.setVisibility(View.INVISIBLE);
        }
    }


    public void setDefaultIconId(int shareIconId) {
        mShareIconId = shareIconId;
    }


    public SharePopupWindow() {
        super(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT);
        mController = UMServiceFactory.getUMSocialService("com.umeng.share");
    }

    public SharePopupWindow(String picurl) {
        super(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT);
        this.picurl = picurl;
        mController = UMServiceFactory.getUMSocialService("com.umeng.share");
    }

    public SharePopupWindow(Context context, String picurl, boolean isShowWeiba) {
        super(context);
        this.picurl = picurl;
        this.isShowWeiba = isShowWeiba;
        mController = UMServiceFactory.getUMSocialService("com.umeng.share");
    }

    public SharePopupWindow(int defaultIconId) {
        super(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT);
        this.mShareIconId = defaultIconId;
        picurl = null;
        mController = UMServiceFactory.getUMSocialService("com.umeng.share");
    }


    public String getWxAppId() {
        return sWXAppID;
    }



    private void initViews(Context context) {
        mContext = context;

        if (TextUtils.isEmpty(sWXAppID)) {
            try {
                sWXAppID =
                        context.getPackageManager().getApplicationInfo(context.getPackageName(),
                                PackageManager.GET_META_DATA).metaData
                                .getString(SharePopupWindow.PARAM_WEIXIN_APPKEY);
            } catch (NameNotFoundException e) {
                e.printStackTrace();
            }
        }

        View convertView =
                LayoutInflater.from(context).inflate(R.layout.layout_share_popupwindow, null);
        convertView.findViewById(R.id.share_to_friend).setOnClickListener(mOnClickListener);
        convertView.findViewById(R.id.share_to_weixin).setOnClickListener(mOnClickListener);
        convertView.findViewById(R.id.share_to_sina).setOnClickListener(mOnClickListener);
        convertView.findViewById(R.id.share_to_sms).setOnClickListener(mOnClickListener);
        convertView.findViewById(R.id.share_to_cut).setOnClickListener(mOnClickListener);
        convertView.findViewById(R.id.share_to_qq).setOnClickListener(mOnClickListener);
        convertView.findViewById(R.id.share_to_qqzone).setOnClickListener(mOnClickListener);
        weiba = (LinearLayout) convertView.findViewById(R.id.share_to_weiba);
        convertView.findViewById(R.id.share_to_weiba).setOnClickListener(mOnClickListener);
        convertView.findViewById(R.id.btn_cacel).setOnClickListener(mOnClickListener);
        setBackgroundDrawable(new PaintDrawable(Color.TRANSPARENT));
        setOutsideTouchable(true);
        setFocusable(true);
        setContentView(convertView);

        // 根据屏幕宽度适应不同布局
        if (CommonUtil.isTablet(context)) {
            setWidth(CommonParameter.sScreenWidth * 7 / 10);
        } else {
            setWidth(LayoutParams.MATCH_PARENT);
        }

        setHeight(LayoutParams.WRAP_CONTENT);

        setShowWeiba(isShowWeiba);
    }

    public SharePopupWindow setInfors(Context context, String shareTitle, String shareContent,
            String urlContent) {
        this.mShareTitle = shareTitle;
        this.mShareContent = shareContent;
        this.mShareUrl = urlContent;
        initViews(context);
        return this;
    }

    private String sinaTitle;
    private String shareWXContent;
    private String shareQQContent;

    public SharePopupWindow setInfors(Context context, String sinaTitle, String shareTitle,
            String shareContent, String urlContent) {
        this.sinaTitle = sinaTitle;
        this.mShareTitle = shareTitle;
        this.mShareContent = shareContent;
        this.mShareUrl = urlContent;
        initViews(context);
        return this;
    }

    public SharePopupWindow setInfors(Context context, String sinaTitle, String shareTitle,
            String shareContent, String shareWXContent, String shareQQContent, String urlContent) {
        this.sinaTitle = sinaTitle;
        this.mShareTitle = shareTitle;
        this.mShareContent = shareContent;
        this.shareWXContent = shareWXContent;
        this.shareQQContent = shareQQContent;
        this.mShareUrl = urlContent;
        initViews(context);
        return this;
    }

    private String tid;

    public void setPostTid(String tid) {
        this.tid = tid;
    }

    private String come;

    public void setPostCome(String come) {
        this.come = come;
    }

    private final OnClickListener mOnClickListener = new OnClickListener() {

        @SuppressLint("NewApi")
        @SuppressWarnings("deprecation")
        @Override
        public void onClick(View v) {
            if (isShowing()) {
                dismiss();
            }
            if (v.getId() == R.id.share_to_sina) {//
                shareToSina();
            } else if (v.getId() == R.id.share_to_friend) {
                shareToWXFriend();
            } else if (v.getId() == R.id.share_to_qq) {
                shareQQ();
            } else if (v.getId() == R.id.share_to_qqzone) {
                shareQQZone();
            } else if (v.getId() == R.id.share_to_weiba) {
                // TODO
                shareToWeiba();
            } else if (v.getId() == R.id.share_to_weixin) {//
                shareToWX();
            } else if (v.getId() == R.id.share_to_sms) {//
                sendSMS();
            } else if (v.getId() == R.id.share_to_cut) {//
                ((ClipboardManager) mContext.getSystemService(Context.CLIPBOARD_SERVICE))
                        .setText(mShareUrl);
                Toast.makeText(mContext, R.string.copy_success, Toast.LENGTH_SHORT).show();
            } else if (v.getId() == R.id.btn_cacel) {
            }
        }


    };

    /**
     * 分享到尾巴好友
     */
    private void shareToWeiba() {

        // TODO Auto-generated method stub
        if (UserState.isLogged((Activity) mContext)) {
            Intent intent = new Intent(mContext, QuoteFriendActivity.class);
            intent.putExtra(Constants.KEY_GROUP_FID, "0");
            ((Activity) mContext).startActivityForResult(intent, 937);
        }


    }



    /**
     * @功能描述 : 分享多个已授权平台(功能底层接口)
     */
    private void shareToMultiPlatform() {
        // UMShareMsg shareMsg = new UMShareMsg();
        // shareMsg.mText = mShareContent;
        //
        // mController.postShareMulti(mContext, shareMsg, new
        // MulStatusListener() {
        // =======
        mController.postShareMulti(mContext, new MulStatusListener() {
            @Override
            public void onStart() {
                Toast.makeText(mContext, "开始分享", Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onComplete(MultiStatus snsSt, int st, SocializeEntity entity) {
                Toast.makeText(mContext, snsSt.toString(), Toast.LENGTH_LONG).show();
            }
        }, SHARE_MEDIA.SINA, SHARE_MEDIA.RENREN, SHARE_MEDIA.DOUBAN, SHARE_MEDIA.TENCENT,
                SHARE_MEDIA.QZONE, SHARE_MEDIA.FACEBOOK);
    }

    /**
     * 验证新浪微博是否已经登录
     * 
     * @param context
     * @return
     */
    public boolean isAuthenticatedBySina(Context context) {
        return OauthHelper.isAuthenticated(context, SHARE_MEDIA.SINA);
    }

    public void authSinaWeibo(Context context, final IRequest<Boolean> iRequest) {
        // SsoHandler handler = new SsoHandler(null, null);
        // mController.getConfig().setSsoHandler(handler);
        mController.doOauthVerify(context, SHARE_MEDIA.SINA, new UMAuthListener() {
            @Override
            public void onError(SocializeException e, SHARE_MEDIA platform) {
                iRequest.request(false);
            }

            @Override
            public void onComplete(Bundle value, SHARE_MEDIA platform) {
                iRequest.request(true);
            }

            @Override
            public void onCancel(SHARE_MEDIA arg0) {}

            @Override
            public void onStart(SHARE_MEDIA arg0) {}

        });
    }

    public void directSinaWeiboShare(final Context context, String title, File imageFile) {
        mController.setShareContent(title);
        if (imageFile != null) {
            mController.setShareImage(new UMImage(context, imageFile));
        } else {
            mController.setShareImage(null);
        }
        if (OauthHelper.isAuthenticated(context, SHARE_MEDIA.SINA)) {
            // Toast.makeText(context, "新浪平台已经授权.", Toast.LENGTH_SHORT).show();
            mController.directShare(context, SHARE_MEDIA.SINA, null);
        }
    }

    /**
     * @功能描述 : 授权（功能底层接口）
     */
    public void doOauth(final Context context, String title, File imageFile) {
        // SinaSsoHandler handler = new SinaSsoHandler();
        // mController.getConfig().setSsoHandler(handler);
        mController.setShareContent(title);
        if (imageFile != null) {
            mController.setShareMedia(new UMImage(context, imageFile));
        }
        if (OauthHelper.isAuthenticated(context, SHARE_MEDIA.SINA)) {
            mController.directShare(context, SHARE_MEDIA.SINA, null);
        } else {
            mController.doOauthVerify(context, SHARE_MEDIA.SINA, new UMAuthListener() {
                @Override
                public void onError(SocializeException e, SHARE_MEDIA platform) {}

                @Override
                public void onComplete(Bundle value, SHARE_MEDIA platform) {
                    mController.directShare(context, SHARE_MEDIA.SINA, null);
                }

                @Override
                public void onCancel(SHARE_MEDIA arg0) {}

                @Override
                public void onStart(SHARE_MEDIA arg0) {}

            });
        }
    }

    public void shareToSinaByBackground(final Context context, String title, File imageFile) {
        // SinaSsoHandler handler = new SinaSsoHandler();
        // mController.getConfig().setSsoHandler(handler);
        mController.setShareContent(title);
        if (imageFile != null) {
            mController.setShareMedia(new UMImage(context, imageFile));
        }
        mController.postShareMulti(context, new MulStatusListener() {

            @Override
            public void onStart() {

            }

            @Override
            public void onComplete(MultiStatus arg0, int arg1, SocializeEntity arg2) {}
        }, SHARE_MEDIA.SINA);
    }

    /**
     * 点击按钮分享的
     */
    private void shareToSina() {
        mController.setShareContent(sinaTitle);
        if (!TextUtils.isEmpty(picurl)) {
            mController.setShareMedia(new UMImage(mContext, picurl));
        } else if (0 != mShareIconId) {
            mController.setShareMedia(new UMImage(mContext, mShareIconId));
        }
        // mController.setShareMedia(new UMImage(mContext, picurl));
        mController.getConfig().closeToast();
        mController.postShare(mContext, SHARE_MEDIA.SINA, new SnsPostListener() {
            @Override
            public void onComplete(SHARE_MEDIA arg0, int arg1, SocializeEntity arg2) {
                shareResult(arg1);
                if (arg1 == 200) {
                    shareSend(MoccaApi.VALUE_SINA);
                }
            }

            @Override
            public void onStart() {
                shareGoing();
            }
        });
    }

    /**
     * 点击按钮分享的
     */
    private void shareToWXFriend() {

        // 设置微信朋友圈分享内容
        CircleShareContent circleMedia = new CircleShareContent();
        String content = "";
        if (!TextUtils.isEmpty(shareWXContent)) {
            content = shareWXContent;
        } else {
            content = mShareContent;
        }

        circleMedia.setShareContent(content);
        // 设置朋友圈title
        circleMedia.setTitle(content);
        if (!TextUtils.isEmpty(picurl)) {
            circleMedia.setShareImage(new UMImage(mContext, picurl));
        } else if (0 != mShareIconId) {
            mController.setShareMedia(new UMImage(mContext, mShareIconId));
        }
        circleMedia.setTargetUrl(mShareUrl);
        mController.setShareMedia(circleMedia);
        mController.getConfig().closeToast();
        mController.postShare(mContext, SHARE_MEDIA.WEIXIN_CIRCLE, new SnsPostListener() {
            @Override
            public void onComplete(SHARE_MEDIA arg0, int arg1, SocializeEntity arg2) {
                shareResult(arg1);
                if (arg1 == 200) {
                    shareSend(MoccaApi.VALUE_WXTIMELINE);
                }
            }

            @Override
            public void onStart() {
                shareGoing();
            }
        });
    }

    /**
     * 点击按钮分享的
     */
    private void shareToWX() {

        // 设置微信好友分享内容
        WeiXinShareContent weixinContent = new WeiXinShareContent();
        // 设置title
        weixinContent.setTitle("尾巴圈，我的养宠神器！");
        // 设置分享内容跳转URL
        weixinContent.setTargetUrl(mShareUrl);
        // 设置分享图片
        if (!TextUtils.isEmpty(picurl)) {
            weixinContent.setShareImage(new UMImage(mContext, picurl));
        } else if (0 != mShareIconId) {
            weixinContent.setShareImage(new UMImage(mContext, mShareIconId));
        }
        String content = "";
        if (!TextUtils.isEmpty(shareWXContent)) {
            content = shareWXContent;
        } else {
            content = mShareContent;
        }
        weixinContent.setShareContent(content);

        mController.setShareMedia(weixinContent);
        mController.getConfig().closeToast();
        mController.postShare(mContext, SHARE_MEDIA.WEIXIN, new SnsPostListener() {
            @Override
            public void onComplete(SHARE_MEDIA arg0, int arg1, SocializeEntity arg2) {
                shareResult(arg1);
                if (arg1 == 200) {
                    shareSend(MoccaApi.VALUE_WXSESSION);
                }
            }

            @Override
            public void onStart() {
                shareGoing();
            }
        });
    }

    private void shareSend(String type) {
        HappyPetApplication.get().getMoccaApi()
                .shareSend(come, type, tid, new IRequest<KeyValuePair<Integer, String>>() {

                    @Override
                    public void request(KeyValuePair<Integer, String> t) {
                        if (null != t) {

                            // 分享成功之后，通知详情页面（活动页面需要改变状态）
                            Intent intent = new Intent(Constants.ACTION_SHARE_SUCCESS);
                            intent.putExtra(Constants.KEY_POST_TID, tid);
                            mContext.sendBroadcast(intent);

                            CommonUtil.refurshWeiba(mContext);

                            if (!TextUtils.isEmpty(t.second)) {
                                CommonUtil.showDialog2(mContext, t.second);
                            }
                        }
                    }
                });
    }

    /**
     * --------------QQ--------错误码110404
     */
    private void shareQQ() {
        QQShareContent qqShareContent = new QQShareContent();
        String content = "";
        if (!TextUtils.isEmpty(shareQQContent)) {
            content = shareQQContent;
        } else {
            content = mShareContent;
        }
        // 设置分享文字
        qqShareContent.setShareContent(content);
        // 设置分享title
        qqShareContent.setTitle("尾巴圈，我的养宠神器！");
        // 设置分享图片
        if (!TextUtils.isEmpty(picurl)) {
            qqShareContent.setShareImage(new UMImage(mContext, picurl));
        } else if (0 != mShareIconId) {
            qqShareContent.setShareImage(new UMImage(mContext, mShareIconId));
        }
        // 设置点击分享内容的跳转链接
        qqShareContent.setTargetUrl(mShareUrl);
        mController.setShareMedia(qqShareContent);
        mController.getConfig().closeToast();
        mController.postShare(mContext, SHARE_MEDIA.QQ, new SnsPostListener() {
            @Override
            public void onStart() {
                shareGoing();
            }

            @Override
            public void onComplete(SHARE_MEDIA platform, int eCode, SocializeEntity entity) {
                shareResult(eCode);
                if (eCode == 200) {
                    shareSend(MoccaApi.VALUE_QQ);
                }

            }
        });



    }

    /**
     * --------------QQZone--------调试通过
     */
    private void shareQQZone() {
        String content = "";
        if (!TextUtils.isEmpty(shareQQContent)) {
            content = shareQQContent;
        } else {
            content = mShareContent;
        }
        QZoneShareContent qzone = new QZoneShareContent();
        // 设置分享文字
        qzone.setShareContent(content);
        // 设置点击消息的跳转URL
        qzone.setTargetUrl(mShareUrl);
        // 设置分享内容的标题
        qzone.setTitle("尾巴圈，我的养宠神器！");
        // 设置分享图片
        if (!TextUtils.isEmpty(picurl)) {
            qzone.setShareImage(new UMImage(mContext, picurl));
        } else if (0 != mShareIconId) {
            qzone.setShareImage(new UMImage(mContext, mShareIconId));
        }
        mController.setShareMedia(qzone);
        mController.getConfig().closeToast();
        if (isShowWeiba) {
            mController.directShare(mContext, SHARE_MEDIA.QZONE, new SnsPostListener() {
                @Override
                public void onStart() {
                    shareGoing();
                }

                @Override
                public void onComplete(SHARE_MEDIA platform, int eCode, SocializeEntity entity) {
                    // 40000
                    shareResult(eCode);
                    if (eCode == 200) {
                        shareSend(MoccaApi.VALUE_QQZONE);
                    }
                }


            });
        } else {
            mController.postShare(mContext, SHARE_MEDIA.QZONE, new SnsPostListener() {
                @Override
                public void onStart() {
                    shareGoing();
                }

                @Override
                public void onComplete(SHARE_MEDIA platform, int eCode, SocializeEntity entity) {
                    // 40000
                    shareResult(eCode);
                    if (eCode == 200) {
                        shareSend(MoccaApi.VALUE_QQZONE);
                    }
                }


            });

        }



    }

    /**
     * --------------TencentWB--------需要平台注册
     */
    private void shareTencentWB() {

        if (!OauthHelper.isAuthenticated(mContext, SHARE_MEDIA.TENCENT)) {
            mController.doOauthVerify(mContext, SHARE_MEDIA.TENCENT, new UMAuthListener() {
                @Override
                public void onStart(SHARE_MEDIA platform) {
                    Toast.makeText(mContext, "授权开始", Toast.LENGTH_SHORT).show();
                }

                @Override
                public void onError(SocializeException e, SHARE_MEDIA platform) {
                    Toast.makeText(mContext, "授权错误", Toast.LENGTH_SHORT).show();
                }

                @Override
                public void onComplete(Bundle value, SHARE_MEDIA platform) {
                    Toast.makeText(mContext, "授权完成", Toast.LENGTH_SHORT).show();
                    // 获取相关授权信息或者跳转到自定义的分享编辑页面
                    String uid = value.getString("uid");
                }

                @Override
                public void onCancel(SHARE_MEDIA platform) {
                    Toast.makeText(mContext, "授权取消", Toast.LENGTH_SHORT).show();
                }
            });
        }

        // 设置腾讯微博SSO handler
        // mController.getConfig().setSsoHandler(new TencentWBSsoHandler());

        if (!TextUtils.isEmpty(picurl)) {
            mController.setShareMedia(new UMImage(mContext, picurl));
        } else if (0 != mShareIconId) {
            mController.setShareMedia(new UMImage(mContext, mShareIconId));
        }
        // wxHandler.setCircleTitle(mShareTitle);
        mController.setShareContent(mShareContent);
        mController.postShare(mContext, SHARE_MEDIA.TENCENT, new SnsPostListener() {
            @Override
            public void onComplete(SHARE_MEDIA arg0, int arg1, SocializeEntity arg2) {
                shareResult(arg1);
            }

            @Override
            public void onStart() {}
        });

    }

    private void shareGoing() {
        Toast.makeText(mContext, R.string.share_going, Toast.LENGTH_SHORT).show();
    }

    private void shareResult(int code) {
        if (code == 200) {
            Toast.makeText(mContext, R.string.share_success, Toast.LENGTH_SHORT).show();
        } else {
            Toast.makeText(mContext, R.string.share_failed, Toast.LENGTH_SHORT).show();
        }
    }

    private Intent sendSMS() {
        Intent intent = new Intent(Intent.ACTION_SENDTO);
        intent.putExtra("sms_body", mShareContent);
        intent.setData(Uri.parse("smsto:" + toSafeString("")));
        return intent;
    }

    private String toSafeString(Object obj) {
        if (null == obj) {
            return "";
        }
        return obj.toString();
    }
}
